<?php
/* --------------------------------------------------------------
   LogfileServiceRepository.inc.php 2018-08-22
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2018 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/
declare(strict_types=1);

namespace Gambio\Admin\Modules\Logfiles\Repository;


use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Query\QueryBuilder;
use Gambio\Core\Application\Application;
use Gambio\Core\Application\ValueObjects\Environment;
use Gambio\Core\Configuration\App\ConfigurationService;

class LogfileServiceRepository
{

    private const ACTIVE_KEY = "cronjobs/DeleteLogs/active";

    private const THRESHOLD_KEY = "cronjobs/DeleteLogs/olderThan";

    private Environment $environment;
    public function __construct(
        private Application $application,
        private ConfigurationService $configurationService
    )
    {
        $this->environment = $this->application->get(Environment::class);
    }

    public function findConfiguration(): array
    {
        return [
            'active' => $this->configurationService->get(self::ACTIVE_KEY),
            'threshold' => $this->configurationService->get(self::THRESHOLD_KEY),
        ];
    }

    /**
     * @throws Exception
     */
    public function saveConfiguration(int|null $threshold = null, bool|null $active = null): void
    {
        if(
            $this->environment->isCloud()
            || (
            !$this->configurationService->has(self::ACTIVE_KEY)
            && !$this->configurationService->has(self::THRESHOLD_KEY)
            )
        ) {
            $this->configurationService->save(self::ACTIVE_KEY, 'true');
            $this->configurationService->save(self::THRESHOLD_KEY, '2');
            return;
        }

        if (empty($threshold) && empty($active)) {
            return;
        }

        $active = $active ? 'true' : 'false';

        $threshold = (string)$threshold;

        $this->configurationService->save(self::ACTIVE_KEY, $active);

        $this->configurationService->save(self::THRESHOLD_KEY, $threshold);
    }
}